#include "NZ/UDPClient.h"
UDPClient::UDPClient(QWidget *parent)
    : QDialog(parent)
{
    m_udpSocket.bind(8080);   //建立监听
    connect(&m_udpSocket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));   //接收准备

    dateLabel = new QLabel(tr("Date"));
    timeLabel = new QLabel(tr("Time"));
    tempLabel = new QLabel(tr("Temp"));
    humLabel  = new QLabel(tr("Hum"));
    altiLabel = new QLabel(tr("Alti"));
    dateEdit  = new QLineEdit();
    timeEdit  = new QLineEdit();
    tempEdit  = new QLineEdit();
    humEdit   = new QLineEdit();
    altiEdit  = new QLineEdit();

    QGridLayout *gLayout = new QGridLayout;
    gLayout->addWidget(dateLabel, 0, 0);
    gLayout->addWidget(dateEdit, 0, 1);
    gLayout->addWidget(timeLabel, 1, 0);
    gLayout->addWidget(timeEdit, 1, 1);
    gLayout->addWidget(tempLabel, 2, 0);
    gLayout->addWidget(tempEdit, 2, 1);
    gLayout->addWidget(humLabel, 3, 0);
    gLayout->addWidget(humEdit, 3, 1);
    gLayout->addWidget(altiLabel, 4, 0);
    gLayout->addWidget(altiEdit, 4, 1);

    setLayout(gLayout);

}

UDPClient::~UDPClient()
{
}

void UDPClient::processPendingDatagrams()
{
    QByteArray datagram;
    do{
        datagram.resize(m_udpSocket.pendingDatagramSize());
        m_udpSocket.readDatagram(datagram.data(), datagram.size());  //接收数据
    }while( m_udpSocket.hasPendingDatagrams() );

    QDateTime dateTime;
    double temperature;
    double humidity;
    double altitude;

    QDataStream in(&datagram, QIODevice::ReadOnly);
    in.setVersion(QDataStream::Qt_4_7);
    in >> dateTime >> temperature >> humidity >> altitude;

    dateEdit->setText(dateTime.date().toString());
    timeEdit->setText(dateTime.time().toString());
    tempEdit->setText(tr("%1 C").arg(temperature));
    humEdit->setText(tr("%1 %").arg(humidity));
    altiEdit->setText(tr("%1 m").arg(altitude));
}
